package cn.xiyun.xiyuncc.service.impl;

import cn.xiyun.xiyuncc.domain.PayFlow;
import cn.xiyun.xiyuncc.domain.PayOrder;
import cn.xiyun.xiyuncc.dto.AlipayNotifyDto;
import cn.xiyun.xiyuncc.service.IPayFlowService;
import cn.xiyun.xiyuncc.service.IPayOrderService;
import cn.xiyun.xiyuncc.service.IPayResultProcessingService;
import com.alibaba.fastjson.JSON;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.common.Client;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

@Service
public class PayResultProcessingServiceImpl implements IPayResultProcessingService {

    @Autowired
    private IPayOrderService payOrderService;
    @Autowired
    private IPayFlowService payFlowService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    /**
     * 回调结果处理
     */
    @Override
    public String payNotifyCallback(AlipayNotifyDto alipayNotifyDto) throws Exception {
        // 校验数据是否背篡改
        Map map = JSON.parseObject(JSON.toJSONString(alipayNotifyDto), Map.class);
        Boolean payNotifyBoolean = null;
        try {
            payNotifyBoolean = Factory.Payment.Common().verifyNotify(map);
            if (!payNotifyBoolean) return "fail";
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        // 判断支付单是否存在
        PayOrder payOrder = payOrderService.selectOrderNo(alipayNotifyDto.getOut_trade_no());
        if (payOrder == null) return "fail";
        // 根据订单号查询PayFlow表数据
        Wrapper<PayFlow> wrapper = new EntityWrapper<>();
        wrapper.eq("out_trade_no", alipayNotifyDto.getOut_trade_no());
        PayFlow payFlow1 = payFlowService.selectOne(wrapper);
        if (payFlow1 != null) return "success";
        // 将支付数据存入 PayFlow
        PayFlow payFlow = new PayFlow();
        payFlow.setNotifyTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(alipayNotifyDto.getNotify_time()));
        payFlow.setSubject(alipayNotifyDto.getSubject() + ",支付:[" + alipayNotifyDto.getInvoice_amount() + "] 元");
        payFlow.setOutTradeNo(alipayNotifyDto.getOut_trade_no());
        payFlow.setTotalAmount(new BigDecimal(alipayNotifyDto.getInvoice_amount()));
        payFlow.setTradeStatus(alipayNotifyDto.getTrade_status());
        payFlow.setCode(alipayNotifyDto.getCode());
        payFlow.setMsg(alipayNotifyDto.getMsg());
        payFlow.setPassbackParams(alipayNotifyDto.getPassback_params());
        payFlow.setPaySuccess(payNotifyBoolean);
        payFlow.setResultDesc(alipayNotifyDto.getNotify_type());
        // payFlowService.insert(payFlow);
        // 更改支付单状态
       // boolean b = payOrderService.updateById(payOrder);
        // 发送消息更改订单状态
        //封装消息
        Message<String> message = MessageBuilder.withPayload(alipayNotifyDto.getOut_trade_no()).build();
        //发送事务消息 修改支付单与订单状态为支付成功
        rocketMQTemplate.sendMessageInTransaction(
                //这里和事务监听器里面的事务组保持一致
                "Transaction-AlipayNotify-group",
                //topic:tag
                "Alipay_Notify_topic:Alipay_Notify_tags", message, JSON.toJSON(payFlow));

        return "success";
    }
}
